package com.voicechat.firstmet;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.os.Vibrator;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.tencent.TIMLogLevel;
import com.tencent.TIMManager;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.adapter.CommonConstants;
import com.tencent.ilivesdk.core.ILiveRoomConfig;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.qalsdk.sdk.MsfSdkUtils;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.utils.UMUtils;
import com.umeng.socialize.PlatformConfig;
import com.voicechat.firstmet.client.ForegroundCallbacks;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.imcontrol.MessageEvent;
import com.voicechat.firstmet.net.LocationService;
import com.voicechat.firstmet.utils.SPUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import io.realm.DynamicRealm;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmMigration;

/**
 * 模块描述：主控制器
 */
public class App extends MultiDexApplication {
    //public class App extends MobApplication {
    private static final String TAG = "MultiDexApplication";
    private static final String appVersion = "1.0";
    /**
     * 创建本身
     */
    private static App sInstance;

    /**
     * 用于存放所有启动的Activity的集合
     */
    private List<Activity> oList;
    /**
     * 创建一个本地数据库帮助类
     */
   // private DBHelper dbHelper;
    public Vibrator mVibrator;

    //获取正在运行的activity
    public Activity runningActivity;
    public LocationService locationService;
    private static Context context;
    public void setRunningActivity(Activity runningActivity) {
        this.runningActivity = runningActivity;
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        sInstance = this;
        /*清空所有的loger打印信息*/
        //创建运行着的activity集合
        oList = new ArrayList<>();
        //初始化创建SharedPreferences
        SPUtils.createSharedPreferences(this);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

      /* Realm数据库配置 */
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .name("firstMet.realm")
                .schemaVersion(1)
                .migration(new RealmMigration() {
                    @Override
                    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

                    }
                })
                .build();
        Realm.setDefaultConfiguration(config);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        SDKInitializer.initialize(this);
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
        SDKInitializer.setCoordType(CoordType.BD09LL);
        locationService = new LocationService(getApplicationContext());
        // 判断仅在主线程进行初始化
        if (MsfSdkUtils.isMainProcess(this)) {
            ILiveSDK.getInstance().setChannelMode(CommonConstants.E_ChannelMode.E_ChannelIMSDK);
            // 初始化iLiveSDK  测试
            //ILiveSDK.getInstance().initSdk(this, 1400147846, 36862);
            ILiveSDK.getInstance().initSdk(this,1400147846);
            // 初始化iLiveSDK  正式
           // ILiveSDK.getInstance().initSdk(this, 1400172361, 36862);
           //// ILiveSDK.getInstance().initSdk(this,1400172361);
            // 初始化iLiveSDK房间管理模块
            ILiveRoomManager.getInstance().init(new ILiveRoomConfig());
            //关闭log日志
            TIMManager.getInstance().setLogLevel(TIMLogLevel.OFF);
        }
        //初始化消息监听
        MessageEvent.getInstance();
        //长链接重连
        initAppStatusListener();
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }
            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
        UMConfigure.setLogEnabled(true);
        //友盟初始化
        UMConfigure.init(this,"5c0e14c5b465f5618f0000d5"
                ,"umeng", UMConfigure.DEVICE_TYPE_PHONE,"");//58edcfeb310c93091c000be2 5965ee00734be40b580001a0
        UMUtils.setChannel(this, AnalyticsConfig.getChannel(context));
        MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_UM_NORMAL);
        // 打开统计SDK调试模式
        UMConfigure.setLogEnabled(true);
        //豆瓣RENREN平台目前只能在服务器端配置
        PlatformConfig.setQQZone("101504537", "c65ddc94de699fb70014e891adad7fe0");
        PlatformConfig.setWeixin("wxac01dfc5b7f1a911", "612e46ce893d451159aabd9dac869da6");
        JPushInterface.setDebugMode(false); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush\
       // Log.i(TAG, "onCreate: ---getRegistrationID---"+JPushInterface.getRegistrationID(context));
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }
    private void initAppStatusListener() {
        ForegroundCallbacks.init(this).addListener(new ForegroundCallbacks.Listener() {
            @Override
            public void onBecameForeground() {
                Log.i("WsManager","应用回到前台调用重连方法");
                BroadcastManager.getInstance(context).sendBroadcast(MessageEvent.WS_MANAGER);
            }
            @Override
            public void onBecameBackground() {

            }
        });
    }
    /**
    * @method
    * @description 停止服务
    * @date: 2018/11/19 15:56
    * @author: ljp
    * @return
    */
    public  void setStop(){
        if(locationService != null){
            locationService.stop();

        }
    }
    public static Context getContext() {
        return context;
    }
    public void initCallClick(){
        //监听是否在后台运行
      //  registerActivityLifecycleCallbacks(new ApplicationListener());
    }
    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 得到本身
     */
    public static App getInstance() {
        return sInstance;
    }


    /**
     * 添加单个Activity
     *
     * @param activity
     */
    public void addActivity_(Activity activity) {
       // Log.i(TAG, "addActivity_: ------"+activity_imessage);
        // 判断当前集合中不存在该Activity
        if (!oList.contains(activity)) {
            oList.add(activity);//把当前Activity添加到集合中
        }
    }

    /**
     * 销毁单个Activity
     *
     * @param activity
     */
    public void removeActivity_(Activity activity) {
        if (oList.contains(activity)) {
            oList.remove(activity);//从集合中移除
            activity.finish();//销毁当前Activity
        }
    }

    /**
     * 销毁所有的Activity
     */
    public void removeAllActivity_() {
        //通过循环，把集合中的所有Activity销毁
        for (Activity activity : oList) {
            activity.finish();
        }
        oList.clear();
    }

    /**
     * 销毁所有的除开MainActivity的Activity
     */
    public void removeAllExceptMainActivity() {
        Activity a = null;
        for (Activity activity : oList) {
            if (activity instanceof MainActivity) {
                a = activity;
            } else {
                activity.finish();
            }
        }
        oList.clear();
        oList.add(a);
    }


    public Activity getRunningActivity() {
        return runningActivity;
    }
}
